<template>
  <el-dialog
    class="public-dialog"
    :title="title"
    width="560"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
  >
    <div>
      <VForm
        ref="form"
        :fieldList="fieldList"
        :options="formOptions"
        :rules="rules"
        :originOption="originOption"
      />
      <div
        v-if="tips"
        class="flex text-[12px] text-[#9DA1AD] leading-[17px] whitespace-pre-wrap"
      >
        <span class="flex flex-shrink-0 mr-[2px] iconfont icon-hint_line"></span>
        {{ tips }}
      </div>
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSave">
          {{ confirmButtonText }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import VForm from '@/components/Form/index.vue'

const props = defineProps({
  confirmButtonText: { type: String, default: '保存' },
  title: { type: String, default: '' },
  modelValue: { type: Boolean, default: false },
  rules: { type: Object, default: () => ({}) },
  tips: { type: String, default: '' },
  loading: { type: Boolean, default: false },
  inputLabel: { type: String, default: '' },
  fieldOptions: {
    type: Array,
    default: () => [
      {
        field: 'input',
        type: 'textarea',
        label: '',
        style: { width: '100%'},
        autosize: { minRows: 2, maxRows: 6 },
        full: true,
      },
    ],
  },
  originOption: { type: Object, default: () => ({}) },
})

const emit = defineEmits(['update:modelValue', 'submit'])

const form = ref()
const fieldList = ref([])

watch(
  () => [props.fieldOptions, props.inputLabel],
  val => {
    const [options, label] = val
    fieldList.value = options
    if (label && fieldList.value.length) {
      fieldList.value[0].label = label
    }
  },
  { immediate: true }
)

const handleSave = async () => {
  try {
    const formValues = await form.value.submit()
    emit('submit', formValues)
  } catch (e) {
    console.error(e)
  }
}

const handleClose = refresh => {
  emit('update:modelValue', false)
  form.value.resetForm()
  if (refresh) emit('refresh')
}

const formOptions = {
  labelPosition: 'left',
}
</script>
<style lang="scss" scoped>
:deep(.el-form-item__label){
  width: 100px;
}
</style>
